<script lang="jsx" setup>
import { onMounted, ref } from 'vue';
import { Graph } from '@antv/x6';
import { getProcess } from '@/service/api/modules/trace/read-the-dock';
import ListContent from './modules/tabs-content.vue';
import list from './modules/data.js';

const containerRef = ref(null);
const active = ref('graph');
const graph = ref(null);
const colors = {
  0: 'rgb(173,185,202)',
  1: 'red',
  2: 'rgb(255,220,0)',
  3: 'rgb(234,234,16)',
  4: 'green'
};

// 拓扑图初始化
function initGraph() {
  graph.value = new Graph({
    container: containerRef.value,
    // 平移
    panning: {
      enabled: true,
      eventTypes: ['leftMouseDown']
    },
    // 缩放
    mousewheel: {
      enabled: true
    },
    background: {
      color: '#F2F7FA'
    },
    translating: {
      restrict(view) {
        const cell = view.cell;
        if (cell.isNode()) {
          const parent = cell.getParent();
          if (parent) {
            return parent.getBBox();
          }
        }

        return null;
      }
    }
  });
}

const cunrentData = ref(null);
function initEvent() {
  graph.value.on('node:click', ({ node }) => {
    // eslint-disable-next-line no-underscore-dangle
    const nodeId = node?._parent?.id || node.id;
    const nodeItem = list.find(item => item.id === nodeId);
    let data = null;

    if (nodeItem?.children?.length) {
      data = nodeItem.children.find(item => item.id === node.id);
    } else {
      data = nodeItem;
    }
    console.log(data);

    if (!data.processId) {
      window.$message.warning('该制程暂无读码设备信息!');
      return;
    }
    cunrentData.value = data;
    active.value = 'list';
  });
}

let processList = [];
// 获取工序信息
function getProcessList() {
  getProcess().then(({ data, error }) => {
    if (!error) {
      processList = data;
      renderNode();
      graph.value.centerContent(); // 居中显示
    }
  });
}

// 获取工序id
function getProcessId(row) {
  const id = processList.find(item => item.processName.toUpperCase() === row.label)?.id || null;
  return id;
}

const width = 180;
const columnCount = 8;

// 渲染节点
function renderNode() {
  list.forEach((item, index) => {
    const row = Math.floor(index / columnCount); // 每行的节点数，例如5个
    const column = index % columnCount;

    // 获取行数
    let x;
    // 偶数列
    if (row % 2 === 0) {
      x = column * width;
    } else {
      // 奇数列
      x = width * columnCount - width * (column + 1);
    }

    if (item.type) {
      const parent = graph.value.addNode({
        id: item.id,
        x, // 列数决定x坐标
        y: row * 91, // 行数决定y坐标
        width: 130,
        height: 55 * item.children.length,
        zIndex: 1,
        // label: 'Parent\n(try to move me)',
        attrs: {
          body: {
            stroke: 'rgb(15,180,240)',
            fill: 'transparent'
          }
        }
      });
      item.children.forEach((child, idx) => {
        child.processId = getProcessId(child);
        const childNode = graph.value.addNode({
          id: child.id,
          shape: 'rect',
          x: x + 5, // 列数决定x坐标
          y: row * 92 - idx * -item.yCount, // 行数决定y坐标
          width: 120,
          height: 40,
          label: child.label,
          attrs: {
            body: {
              stroke: 'rgb(15,180,240)',
              strokeWidth: 1,
              fill: colors[child.state],
              rx: 6,
              ry: 6,
              cursor: 'pointer'
            },
            label: {
              fill: child.textColor || '#000',
              fontSize: 14,
              fontWeight: 'bold',
              cursor: 'pointer'
            }
          }
          //   tools: child.hasIPQC
          //     ? [
          //         {
          //           name: 'button',
          //           args: {
          //             markup: [
          //               {
          //                 tagName: 'circle',
          //                 selector: 'button',
          //                 attrs: {
          //                   stroke: 'rgb(15,180,240)',
          //                   fill: '#fff',
          //                   cursor: 'pointer'
          //                 }
          //               },
          //               {
          //                 tagName: 'text',
          //                 textContent: 'IPQC',
          //                 selector: 'span',
          //                 attrs: {
          //                   fill: '#fff',
          //                   fontWeight: 'bold',
          //                   fontSize: 12,
          //                   textAnchor: 'middle',
          //                   pointerEvents: 'none'
          //                 }
          //               }
          //             ],
          //             x: '100%',
          //             y: '100%',
          //             offset: { x: -20, y: -28 }
          //           }
          //         }
          //       ]
          //     : []
        });
        parent.addChild(childNode);
      });
    } else {
      item.processId = getProcessId(item);
      graph.value.addNode({
        id: item.id,
        shape: 'rect',
        x, // 列数决定x坐标
        y: row * 100, // 行数决定y坐标
        width: 120,
        height: 40,
        label: item.label,
        attrs: {
          body: {
            stroke: 'rgb(15,180,240)',
            strokeWidth: 1,
            fill: colors[item.state],
            rx: 6,
            ry: 6,
            cursor: 'pointer'
          },
          label: {
            fill: item.textColor || '#000',
            fontSize: 14,
            fontWeight: 'bold',
            cursor: 'pointer'
          }
        }
        // tools: item.hasIPQC
        //   ? [
        //       {
        //         name: 'button',
        //         args: {
        //           markup: [
        //             {
        //               tagName: 'circle',
        //               selector: 'button',
        //               attrs: {
        //                 width: 60,
        //                 stroke: 'rgb(15,180,240)',
        //                 fill: '#fff',
        //                 cursor: 'pointer'
        //               }
        //             },
        //             {
        //               tagName: 'text',
        //               textContent: 'IPQC',
        //               selector: 'icon',
        //               attrs: {
        //                 fill: '#fff',
        //                 fontWeight: 'bold',
        //                 fontSize: 12,
        //                 textAnchor: 'middle',
        //                 pointerEvents: 'none'
        //               }
        //             }
        //           ],
        //           x: '100%',
        //           y: '100%',
        //           offset: { x: -20, y: -28 }
        //         }
        //       }
        //     ]
        //   : []
      });
    }
    if (list.length !== index + 1) {
      graph.value.addEdge({
        shape: 'edge',
        source: item.id,
        target: list[index + 1].id,
        connector: { name: 'smooth' },

        attrs: {
          line: {
            stroke: 'rgb(36,124,254)',
            strokeWidth: 2,
            strokeDasharray: 5,
            targetMarker: 'classic'
            // style: {
            //   animation: 'antv-x6-line 30s infinite linear'
            // }
          }
        }
      });
    }
  });
  console.log('list', list);
}

onMounted(() => {
  initGraph();
  initEvent();
  getProcessList();
});
</script>

<template>
  <div class="read-graph-page h-full w-full p-5px">
    <!-- 流程图 -->

    <ATabs v-model:activeKey="active" type="card" animated>
      <ATabPane key="graph" tab="工序流程图">
        <div class="h-full w-full">
          <div ref="containerRef" class="w-full container"></div>
          <div class="footer flex pl-15px pr-15px">
            <div class="footer-item flex flex-center">
              <div class="mr-5px">说明:</div>
              <div class="label flex flex-center">
                <div class="mr-5px h30px w-50px bg-#FF0000"></div>
                重要制程
              </div>
            </div>

            <div class="footer-item ml-20px flex flex-center">
              <div class="mr-5px">钻码:</div>
              <div class="label flex flex-center">
                <div class="mr-5px h30px w-50px bg-#FFC000"></div>
              </div>
            </div>

            <div class="footer-item ml-20px flex flex-center">
              <div class="mr-5px">读码:</div>
              <div class="label flex flex-center">
                <div class="mr-5px h30px w-50px bg-#EAEA10"></div>
              </div>
            </div>

            <div class="footer-item ml-20px flex flex-center">
              <div class="mr-5px">打码:</div>
              <div class="label flex flex-center">
                <div class="mr-5px h30px w-50px bg-#008000"></div>
              </div>
            </div>
          </div>
        </div>
      </ATabPane>
      <ATabPane key="list" :tab="`${cunrentData?.label || ''}读码设备信息`" :disabled="!cunrentData">
        <ListContent :process-id="cunrentData?.processId" />
      </ATabPane>
      <ATabPane key="listCollect" tab="读码设备信息汇总">
        <ListContent />
      </ATabPane>
    </ATabs>
  </div>
</template>

<style lang="scss" scoped>
.read-graph-page {
  :deep(.ant-tabs) {
    width: 100%;
    height: 100%;
    .ant-tabs-nav {
      margin-bottom: 0;
    }
    .ant-tabs-content-holder {
      height: calc(100% - 46px);
      .ant-tabs-content {
        height: 100%;
      }
    }
  }

  .container {
    height: calc(100% - 50px);
    width: 100% !important;
    max-width: 100% !important;
    .x6-graph-background {
      width: 100% !important;
    }
  }
  .footer {
    height: 50px;
    align-items: center;
  }

  .list {
    position: relative;
    .return-btn {
      position: absolute;
      right: 15px;
      top: 8px;
      z-index: 9999;
    }
  }
}
</style>
